package com.tywj.lib.net.retrofit.model

import android.os.SystemClock
import java.util.*

/**
 * <pre>
 *     author : June Yang
 *     time   : 2020/5/7
 *     desc   : 文件下载或上传进度
 *     version: 1.0.0
 * </pre>
 */
class Progress {

    // 总字节长度, byte
    var totalSize: Long = 0
    // 已经完成的进度，0-1
    var fraction: Float = 0f
        private set
    // 已经完成的大小, byte
    var currentSize: Long = 0
        private set
    // 网速，byte/s
    var speed: Long = 0
        private set

    // 每一小段时间间隔的网络流量
    private var tempSize: Long = 0
    // 最后一次刷新的时间
    private var lastRefreshTime: Long = 0
    // 网速做平滑的缓存，避免抖动过快
    private val speedBuffer: ArrayList<Long>

    companion object {
        // 回调刷新时间（单位ms）
        private const val REFRESH_TIME = 300
    }

    init {
        lastRefreshTime = SystemClock.elapsedRealtime()
        totalSize = -1
        speedBuffer = ArrayList()
    }

    /**
     * 修改Progress
     * @param writeSize 本次传输大小
     * @param updateProgress 在界面上更新进度
     */
    fun changeProgress(writeSize: Long, updateProgress: (Progress) -> Unit?) {
        currentSize += writeSize
        tempSize += writeSize

        val currentTime = SystemClock.elapsedRealtime()
        val isNotify = currentTime - this.lastRefreshTime >= REFRESH_TIME
        if (isNotify || currentSize == totalSize) {
            var diffTime = currentTime - lastRefreshTime
            if (diffTime == 0L) diffTime = 1
            fraction = currentSize * 1.0f / totalSize
            speed = bufferSpeed(tempSize * 1000 / diffTime)
            lastRefreshTime = currentTime
            tempSize = 0
            updateProgress.invoke(this)
        }
    }

    /**
     * 平滑网速，避免抖动过大
     */
    private fun bufferSpeed(speed: Long): Long {
        speedBuffer.add(speed)
        if (speedBuffer.size > 10) {
            speedBuffer.removeAt(0)
        }
        var sum: Long = 0
        for (speedTemp in speedBuffer) {
            sum += speedTemp
        }
        return sum / speedBuffer.size
    }
}